import {Injectable} from "@angular/core";
import {Observable, of} from "rxjs";
import {HttpClient} from "@angular/common/http";
import {map} from "rxjs/operators";

@Injectable({
  providedIn:'root'
})
export class UserService {
  private user:{} = null;
  constructor(private httpClient:HttpClient){}
  getUser():Observable<any>{
    if(this.user==null){
      return this.httpClient.get("http://122.224.253.202:20020/x_organization_assemble_authentication/jaxrs/authentication",{withCredentials:true}).pipe(map(res=>{
        if(res['data']['name']=='anonymous'){
          return null;
        }else{
          return res['data'];
        }
      }))
    }else {
      return of(this.user);
    }
  }

  login(username:string,password:string):Observable<any>{
    return this.httpClient.post('http://122.224.253.202:20020/x_organization_assemble_authentication/jaxrs/authentication',{
      "credential":username,
      "password":password
    },{withCredentials:true}).pipe(map(res=>{
      this.user = res["data"];
      return res;
    }));
  }

  logout(){
    this.httpClient.delete('http://122.224.253.202:20020/x_organization_assemble_authentication/jaxrs/authentication',{withCredentials:true}).subscribe(res=>{

    });
  }
}

